<?php

namespace App\Store\Services\Goods;


use App\Store\Models\Basic\GoodsCategory;

class GoodsAllotService
{
    /**
     * 检查商品调拨
     * @param $cp_id
     * @param $target_store_id
     * @param $goods_list
     * @param $accountinfo
     * @return array[]
     */
    public function checkAllotGoods($cp_id, $target_store_id, $goods_list,$accountinfo)
    {
        $allot_info_data = [];
        $goodsError = [];
        $goods_category_ids = array_column($goods_list, 'goods_category_id');
        $cateList = GoodsCategory::query()
            ->where('store_id', intval($accountinfo['store_ids'] ?? 0))
            ->whereIn('id', $goods_category_ids)
            ->where('cp_id', $cp_id)
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        foreach ($goods_list as $goods) {
            $cate = $cateList[$goods['goods_category_id']] ?? [];
            if (empty($cate)) {
                $goodsError[] = $goods['goods_sn_code'] . '商品类别不存在不能调拨';
            } else {

                $category_name = $goods['goods_category']['category_name']?? 0;
                // 查询目标店设置分类属性是否一致
                $targetCate = GoodsCategory::query()
                    ->where('store_id', $target_store_id)
                    ->where('cp_id', $cp_id)
                    ->where('category_name', $category_name)
                    ->where('goods_cabinetgroup_id', $cate['goods_cabinetgroup_id'])
                    ->where('goods_metal_id', $cate['goods_metal_id'])
                    ->where('is_recovery', $cate['is_recovery'])
                    ->where('is_sujin', $cate['is_sujin'])
                    ->where('is_maintenance_price', $cate['is_maintenance_price'])
                    ->first();
                if (empty($targetCate)) {
                    $goodsError[] = empty($goods['goods_sn_code'])? '目的门店商品类别不存在':'目的门店商品：'.$goods['goods_sn_code'].'类别不存在';
                } else {
                    $cate = $targetCate->toArray();
                    $goods['target_category_id'] = $cate['id'];
                    $allot_info_data[] = $goods;
                }
            }

        }


        return ['data' => $allot_info_data, 'err_msg' => $goodsError];
    }
}
